﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;

namespace Alogient.Cameleon.Sdk.UrlRewriting
{
    /// <summary>
    /// The Form class extends the HtmlForm HTML control by overriding its RenderAttributes()
    /// method and NOT emitting an action attribute.
    /// </summary>
    public class CMForm : System.Web.UI.HtmlControls.HtmlForm
    {
        /// <summary>
        /// The RenderAttributes method adds the attributes to the rendered &lt;form&gt; tag.
        /// We override this method so that the action attribute is not emitted.
        /// </summary>
        /// <param name="writer">
        /// The writer.
        /// </param>
        protected override void RenderAttributes(HtmlTextWriter writer)
        {
            // write the form's name
            writer.WriteAttribute("name", this.Name);
            this.Attributes.Remove("name");

            // write the form's method
            writer.WriteAttribute("method", this.Method);
            this.Attributes.Remove("method");

            var actionUrl = HttpContext.Current.Items["originalUrl"] as string;

            if (string.IsNullOrEmpty(actionUrl))
            {
                actionUrl = HttpContext.Current.Request.Url.ToString();
            }

            writer.WriteAttribute("action", actionUrl);

            // finally write all other attributes
            this.Attributes.Render(writer);

            if (this.ID != null)
            {
                writer.WriteAttribute("id", this.ClientID);
            }
        }
    }
}
